package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponConsumerReqDTO;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;


    /**
     * 查询优惠券领取记录列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<CouponInfoResDTO> pageList(CouponOperationPageQueryReqDTO dto) {
        //1.构建请求条件
        //2.查询coupon 数据库列表
        List<Coupon> couponList = list(Wrappers.<Coupon>lambdaQuery().eq(Coupon::getActivityId, dto.getActivityId()));
        //3.Bean拷贝为CouponInfoResDTO类型
        List<CouponInfoResDTO> couponInfoResDTOS = BeanUtils.copyToList(couponList, CouponInfoResDTO.class);
        //4.调用分页助手返回
        return PageHelperUtils.selectPage(dto, () -> couponInfoResDTOS);
    }

    /**
     * 查询自己领取的优惠券
     *
     * @param dto
     * @return
     */
    @Override
    public List<CouponInfoResDTO> pageCouponList(CouponConsumerReqDTO dto) {
        //1.根据当前用户的id查询对应状态的优惠券
        LambdaQueryWrapper<Coupon> queryWrapper = Wrappers.<Coupon>lambdaQuery();
        queryWrapper.eq(Coupon::getStatus, dto.getStatus())
                .eq(dto.getLastId() != null, Coupon::getId, dto.getLastId());
        List<Coupon> couponList = list(queryWrapper);
        return BeanUtils.copyToList(couponList, CouponInfoResDTO.class);
    }
}
